package edu.friday.repository.custom.impl;

import edu.friday.model.SysMenu;
import edu.friday.repository.custom.SysMenuCustomRepository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;

import java.util.List;

public class SysMenuCustomRepositoryImpl implements SysMenuCustomRepository {
    @PersistenceContext
    private EntityManager em;


    String JOIN_ROLE_MENU = "left join sys_role_menu rm on m.menu_id " +
            " = rm.menu_id ";
    String JOIN_USER_ROLE = "left join sys_user_role ur on rm.role_id =  ur.role_id ";

    String SELECT=" select distinct m.* from sys_menu m ";

    String ORDER_BY = " order by parent_id, order_num ";

    String JOIN_ROLE = "left join sys_role ro on ur.role_id = ro.role_id ";

    @Override
    public List<SysMenu> selectMenuListByUserId(SysMenu sysMenu, Long userId) {
        boolean queryMenuName = null !=sysMenu.getMenuName() &&!sysMenu.getMenuName().equals("");
        boolean queryVisible = null !=sysMenu.getVisible();

        String sql=new String();
        sql+=SELECT;

        sql+=JOIN_ROLE_MENU;

        sql+=JOIN_USER_ROLE;

        sql+=" where ur.user_id = :userId ";

        if(queryMenuName){
            sql+=" and m.menu_name like concat('%',:menuName,'%')";
        }
        if(queryVisible){
            sql+=" and rm.visible = :visible ";
        }

        sql+=ORDER_BY;
        Query query = em.createNativeQuery(sql,SysMenu.class).setParameter("userId",userId);
        if (queryMenuName){
            query.setParameter("menuName",sysMenu.getMenuName());
        }
        if (queryVisible){
            query.setParameter("visible",sysMenu.getVisible());
        }
        return query.getResultList();
    }
}
